package com.kzw.oa.byxt.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kzw.core.mapper.Jackson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.ContextUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.StringUtil;
import com.kzw.core.web.action.BaseAction;
import com.kzw.oa.byxt.model.Subject;
import com.kzw.oa.byxt.model.YuXuan;
import com.kzw.oa.byxt.service.StudentService;
import com.kzw.oa.byxt.service.SubjectService;
import com.kzw.oa.byxt.service.YuXuanService;
import com.kzw.oa.comm.vo.Msg;
import com.kzw.oa.misc.util.ExportWordUtil;
import com.kzw.oa.misc.vo.WordVo;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.model.system.Department;
import com.kzw.oa.service.ext.AppUserService2;
import com.kzw.oa.util.JSON;
import com.kzw.oa.util.JSON2;

@Controller
@Scope("prototype")
public class YuXuanAction extends BaseAction {
	@Autowired
	private AppUserService2 appUserService2;
	@Autowired
	private YuXuanService yuXuanService;	
	@Autowired
	private SubjectService subjectService;	
	@Autowired
	private StudentService studentService;	
	
	private YuXuan yuXuan;
	private Long oid;

	/**
	 * 添加的数据字符串中应该不能有html标签
	 * 
	 * 
	 * 如果在外部更改了word的文件数据，要刷新一下资源区，才能使用
	 * 
	 * C1 - C6 方块
	 * C7 指导老师名字
	 * C8学生姓名
	 * C9学号
	 * C10班级
	 * C11 申报题目
	 * C12 要求
	 * C13 起止周数
	 * C14毕业实习时间及其地质
	 * C15 主要完成工作
	 * C16老师职称
	 */
	public void exportWord() {
		
		HttpServletRequest request = getRequest();
		
		//学生的userId
		String[] ids = request.getParameter("userIds").split(",");
	
		// 创建数据模型
		Map<String, Object> dataMap = new HashMap<String, Object>();
		
		String fileName = "选题申报表.doc";
		
		List<WordVo> vos = new ArrayList<>();
		int index = 1; //序号
		for(String oid : ids) {
//			"■   "; "□  ";
			AppUser student = studentService.get(Long.parseLong(oid));
			Subject subject = subjectService.findUniqueByHQL("from Subject  where student = ?", student);
			WordVo vo = new WordVo();
			 
			 // 此学生没有选题
			if(subject == null) {
//				vo.setC15("暂无");
			} else {
				switch(subject.getFromType().getDicId().intValue()) {
					case 104:vo.setC1("■");break;   //教师科研
					case 105:vo.setC2("■");break;    //教师自拟
					case 106:vo.setC3("■");break;   //学生自选
					case 107:vo.setC4("■");break;   //生产实践
					case 108:vo.setC5("■");break;    //实验室建设
					case 109:vo.setC6("■");break;    //其他
				}
				
				vo.setC7(subject.getTeacher().getFullname());
				vo.setC16(subject.getTeacher().getDutyNames());
				vo.setC11(subject.getName());
				vo.setC12(noBr(subject.getYaoqiu()));
				vo.setC13(subject.getWeekLen());
				vo.setC14(subject.getShixiInfo());
				vo.setC15(noBr(subject.getSumary()));
			
			}
			
			vo.setXuhao(index + "");
			index++;
			vo.setC8(student.getFullname());
			vo.setC9(student.getUsername());
			vo.setC10(student.getDepartment().getDepName()); //班级
			vo.setC17("软件工程");
			vos.add(vo);

		}
		dataMap.put("vos", vos);
		try {
			ExportWordUtil.exportWord(getRequest(), getResponse(), fileName, "student.xml", dataMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private String noBr(String s) {
		s = s.replaceAll("<br>", "<w:p></w:p>");
		return s;
	}
	/**
	 * 显示我预选过的列表
	 */
	public String listMy() {
		HttpServletRequest request = getRequest();

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		
		AppUser currUser = ContextUtil.getCurrentUser();
		filters.add(new StringPropertyFilter("EQL_student.userId", currUser.getUserId()+""));
		
		// 可以通过结果集的大小来查看当前用户已预选的题目数目
		Page<YuXuan> page = yuXuanService.search2(pageRequest, filters);
		jsonString = new JSON2(page).with(YuXuan.class, "oid", "status", "subject")
						.with(Subject.class, "oid", "name", "teacher")
						.with(AppUser.class, "fullname").toJson();
		return SUCCESS;
	}
	
	/**
	 * 显示所有可预选题目列表
	 */
	public String list() {
		
		HttpServletRequest request = getRequest();

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		filters.add(new StringPropertyFilter("EQI_status", "4"));
		// 为空或小于5
		filters.add(new StringPropertyFilter("LTI_xscnt", "5"));
		
		// 获取当前用户选过的题目
		AppUser currUser = ContextUtil.getCurrentUser();
		if(!currUser.getUserId().equals(AppUser.SUPER_USER)) {
			// 查询该学生所有选过的题目
			if(currUser.getRoleType() == 3) {
				String hql = "select x.subject from YuXuan x where x.student=?";
				List<Subject> subjects = subjectService.findByHQL(hql, currUser);
				for(Subject tm : subjects) {
					filters.add(new StringPropertyFilter("NEL_oid", tm.getOid() + ""));
				}
			}
		}
		
		if (ExtjsUtil.isExport(request)) { // 导出报表
			List<Subject> resultList = subjectService.search(filters);
			request.setAttribute("__exportList", resultList);
			return SUCCESS;
		}

		Page<Subject> page = subjectService.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	
	/**
	 * 找到选中题目的预选信息
	 */
	public String listSelect(){
		// 状态
		String hql = "select x.student from YuXuan as x where x.subject.oid=?";
		List<AppUser> list = yuXuanService.findByHQL(hql, oid);
		jsonString = new JSON2(list, true).with(AppUser.class, "userId", "fullname", "username", "title").toJson();
		return SUCCESS;
	}
	
	/**
	 * 批量删除
	 */
	public String multiDel() {
		String[] ids = getRequest().getParameterValues("ids")[0].split(",");
		
		for(String id : ids) {
			YuXuan yu = yuXuanService.get(Long.parseLong(id));
			int xscnt = yu.getSubject().getXscnt();
			if(xscnt > 0) {
				yu.getSubject().setXscnt(xscnt - 1);
			} 
			subjectService.saveOrUpdate(yu.getSubject());
		}
		yuXuanService.remove(ids);
		jsonString = "{success:true}";
		return SUCCESS;
	}

	/**
	 * 显示详细信息
	 * 
	 * @return
	 */
	public String get() {
		YuXuan yuXuan = yuXuanService.get(oid);
		setJsonString(new JSON(yuXuan).buildWithFilters(2));
		return SUCCESS;
	}

	/**
	 * 添加及保存操作
	 * 	一个题目只能被预选5次
	 */
	public String save() {
		// 最大能预选的题目个数
		int maxSubjects = 10;
		HttpServletRequest request = getRequest();
		
		// 获取当前用户选过的题目
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		AppUser currUser = ContextUtil.getCurrentUser();
		filters.add(new StringPropertyFilter("EQL_student.userId", currUser.getUserId()+""));
		List<YuXuan> yuxuans = yuXuanService.search(filters);
		for(YuXuan yuxuan : yuxuans){
			if(yuxuan.getStatus()==3){
				Msg msg = new Msg(false);
				msg.setMessage("您已预选成功，无法再预选！");
				jsonString = Jackson.me().toJson(msg);
				return SUCCESS;
			}
		}
		
		// 如果用户预选的题目达到10就不能再预选了
		if(yuxuans.size() >= maxSubjects) {
			Msg msg = new Msg(false);
			msg.setMessage("您的预选数目已满10个，无法再预选");
			jsonString = Jackson.me().toJson(msg);
			return SUCCESS;
		}
		
		// 还可以预选的题目
		int kejijiaoSubjects = maxSubjects - yuxuans.size() ;
		// 一次题目只能被预选5次
		String[] ids = request.getParameter("ids").split(",");
		kejijiaoSubjects = kejijiaoSubjects < ids.length ? kejijiaoSubjects : ids.length;
		for(int i = 0; i < kejijiaoSubjects; i++) {
			String id = ids[i];
			if(StringUtils.isBlank(id)) continue;
			
			Subject subject = subjectService.get(Long.parseLong(id));
			int oldXscnt = subject.getXscnt() ;
			if(oldXscnt >= 5) break;
			
			subject.setXscnt(oldXscnt + 1);
			subjectService.saveOrUpdate(subject);
			
			YuXuan yuxuan = new YuXuan();
			yuxuan.setStatus(2);
			yuxuan.setStudent(ContextUtil.getCurrentUser());
			yuxuan.setSubject(subject);
			yuXuanService.saveOrUpdate(yuxuan);
		}
		setJsonString("{success:true}");
		return SUCCESS;
	}

	/**
	 * 导出选中记录数
	 * */
	public String exportSel() {
		HttpServletRequest request = getRequest();
		if (ExtjsUtil.isExport(request)) {
			String sids = request.getParameter("sids");
			List<YuXuan> result = yuXuanService.getByIds(StringUtil.idStrToArr(
					sids, Long.class));
			request.setAttribute("__exportList", result);
		}

		return SUCCESS;
	}
	
	/**
	 * 指派学生：把学生加到预选列表中
	 * 	前提：1）本题目未确认；2）选择的学生预选数<10且未确认
	 * */
	public String addStudent() {
		// 该学生的预选是否已确认
		Subject subject = subjectService.get(oid);
		String studentId = getRequest().getParameter("studentId");
		AppUser student = appUserService2.get(Long.parseLong(studentId));
		
		// 是否重复指派
		String hql2 = "select count(*) from YuXuan where student=? and subject=?";
		Long cnt2 = yuXuanService.findUniqueByHQL(hql2, student, subject);
		if(cnt2!=null && cnt2>0) {
			// 报错：不能指派
			Msg msg = new Msg(false);
			msg.setMessage("该学生【"+student.getFullname()+"】已经预选该题目，不可以重复指派!");
			jsonString = Jackson.me().toJson(msg);
			return SUCCESS;
		}
		
		String hql = "select count(*) from YuXuan where status=3 and student=?";
		Long cnt = yuXuanService.findUniqueByHQL(hql, student);
		if(cnt!=null && cnt>0) {
			// 报错：不能指派
			Msg msg = new Msg(false);
			msg.setMessage("该学生【"+student.getFullname()+"】已经预选成功，不能再指派!");
			jsonString = Jackson.me().toJson(msg);
			return SUCCESS;
		}
		
		// 题目的预选加1
		int xscnt = subject.getXscnt();
		subject.setXscnt(xscnt + 1);
		subjectService.saveOrUpdate(subject);
		
		// 指派学生
		Integer xtcnt = student.getXtcnt();
		if(xtcnt == null) xtcnt = 0;
		student.setXtcnt(xtcnt + 1);
		appUserService2.saveOrUpdate(student);
		
		// 增加预选
		YuXuan yuXuan = new YuXuan();
		yuXuan.setStudent(student);
		yuXuan.setSubject(subject);
		yuXuan.setStatus(2);
		yuXuanService.saveOrUpdate(yuXuan);
		
		return SUCCESS;
	}
	
	/**
	 * 指派学生时，列出满足条件的学生
	 * 	1）选择学生的预选数<10或者为null
	 * */
	public String listStudent() {
		PageRequest pageReq = ExtjsUtil.getPageReq(getRequest());
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(getRequest());
		
		List<Object> params = new ArrayList<>();
		String hql0 = ExtjsUtil.getHqlFromFilter(filters, params);
		
		String hql = "from AppUser where" + hql0 + "roleType=3 and (xtcnt is null or xtcnt<10)";
		Page<AppUser> page = appUserService2.findByHQL(pageReq, hql, params.toArray());
		jsonString = new JSON2(page).with(AppUser.class, "userId", "fullname", "username", "department")
						.with(Department.class, "depName").toJson();
		return SUCCESS;
	}
	
	public Long getOid() {
		return oid;
	}

	public void setOid(Long oid) {
		this.oid = oid;
	}

	public YuXuan getYuXuan() {
		return yuXuan;
	}

	public void setYuXuan(YuXuan yuXuan) {
		this.yuXuan = yuXuan;
	}

}
